package main

import (
	"fmt"
	"net"
	"sync"

	"gitee.com/fcu3dx/GoLiaoTian/lib"
	"github.com/bwmarrin/snowflake"
)

type socket struct {
	id snowflake.ID
	conn net.Conn
}

var sockets = make(map[snowflake.ID]*socket)

var lock sync.RWMutex

func wSockets(wSockets func())  {
	lock.Lock()
	defer lock.Unlock()
	wSockets()
}

func rSockets(rSockets func())  {
	lock.RLock()
	defer lock.RUnlock()
	rSockets()
}

func main()  {
	go lib.SignalHandler()

	addr := ":8888"

	ln, err := net.Listen("tcp", addr)

	lib.FatalNotNil(err)

	lib.LogMessage("Listening on ", addr)

	node, err := snowflake.NewNode(1)
	lib.FatalNotNil(err)

	for {
		conn, err := ln.Accept()
		lib.FatalNotNil(err)

		id := node.Generate()

		wSockets(func() {
			sockets[id] = &socket{id, conn}
		})

		// fmt.Fprintf(conn, "Hello, World!\r\n")

		go lib.HandleConnection(
			conn,
			id,
			func(msg string)  {
				rSockets(func()  {
					for k, v := range sockets {
						if k != id {
							fmt.Fprintf(v.conn, "%d:%s\r\n", id, msg)
						}
					}
				})
			},
			func ()  {
				conn.Close()
				wSockets(func()  {
					delete(sockets, id)
				})
			})
	}
}